package com.lanyeo.liver.task

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Point
import com.lanyeo.liver.util.TouchAction
import java.util.LinkedList

abstract class ITask(open val context: Context){
    private var onTaskTouchListener: OnTaskTouchListener? = null
    private var isRunning = false

    /**
     * 需要传入触摸屏幕的事件，否则无法正常工作
     */
    open fun initTask(onTaskTouchListener: OnTaskTouchListener?, taskParams: Any) : Boolean {
        this.onTaskTouchListener = onTaskTouchListener
        return true
    }

    /**
     * @param screen 整个屏幕的截图
     * @param screenRotation 当前屏幕的的状态 Configuration.ORIENTATION_LANDSCAPE 横屏， ORIENTATION_PORTRAIT竖屏
     * @return 返回下一次需要获取屏幕截图的时间点，当为0时，任务结束，单位为毫秒
     */
    abstract fun doTask(screen: Bitmap, screenRotation: Int): Long
    abstract fun finishTask()
    fun isRunning(): Boolean {
        return isRunning
    }

    fun setIsRunning(running: Boolean) {
        isRunning = running
    }

    /**
     * @param 下t秒
     * @return 返回当前时间的下t毫秒
     */
    fun nextTime(t: Float) : Long {
        return System.currentTimeMillis() + (t * 1000).toLong()
    }
    fun nextTime(t: Int) : Long {
        return System.currentTimeMillis() + t * 1000
    }

    /**
     * 点击屏幕事件
     */
    fun touch(x: Int, y: Int, durationTime: Int = 100) {
        touch(Point(x, y), durationTime)
    }
    fun touch(point: Point, durationTime: Int = 100) {
        onTaskTouchListener?.onTouch(listOf(TouchAction(point, 0, durationTime)))
    }
    fun touch(points: List<Point>, waitTime: Int = 500) {
        val actionQueue = LinkedList<TouchAction>()
        for (point in points) {
            actionQueue.offer(TouchAction(point, waitTime))
        }
        onTaskTouchListener?.onTouch(actionQueue)
    }
    fun touch(points: List<TouchAction>) {
        onTaskTouchListener?.onTouch(points)
    }

    /**
     * 单次滑动事件
     */
    fun slide(startPoint: Point, endPoint: Point, durationTime:Int = 1500) {
        onTaskTouchListener?.onTouch(listOf(TouchAction(startPoint, endPoint, durationTime, false)))
    }

    /**
     * 自定义滑动事件
     * 如向上滑动到某个点之后不动
     */
    fun slides(vararg fingers: List<TouchAction>) {
        onTaskTouchListener?.onTouch(*fingers)
    }

    /**
     * 用于server中监听task是否点击
     */
    interface OnTaskTouchListener {
        fun onTouch(vararg fingers: List<TouchAction>)
    }
}